package com.jiutong.meipengdai.ui.fragments;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseApplicationLike;
import com.jiutong.meipengdai.base.BaseFragment;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.entity.EvaluateRecordBean;
import com.jiutong.meipengdai.entity.HouseListRespond;
import com.jiutong.meipengdai.entity.HouseOrRecordBean;
import com.jiutong.meipengdai.entity.ToApplyLoanRespond;
import com.jiutong.meipengdai.http.model.interfaces.OnItemClickListener;
import com.jiutong.meipengdai.http.model.requests.LoanApplyRequest;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.ui.activitys.AddBankCardActivity;
import com.jiutong.meipengdai.ui.activitys.EvaluateActivity;
import com.jiutong.meipengdai.ui.activitys.EvaluateRecordActivity;
import com.jiutong.meipengdai.ui.activitys.HouseListActivity;
import com.jiutong.meipengdai.ui.activitys.LoginActivity;
import com.jiutong.meipengdai.ui.activitys.RealNameActivity;
import com.jiutong.meipengdai.ui.activitys.WaitAuditActivity;
import com.jiutong.meipengdai.ui.adapter.HouseGalleryAdapter;
import com.jiutong.meipengdai.utils.DensityUtil;
import com.jiutong.meipengdai.utils.NumUilt;
import com.jiutong.meipengdai.views.ScaleInTransformer;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.utils.ToastUtil;
import com.jiutong.meipengdai.views.dialog.BaseDialog;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by suxi on 2017/5/24.
 */

public class LoanFragment2v extends BaseFragment {


    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.view_line)
    View viewLine;
    @Bind(R.id.tv_yidiya)
    TextView tvYidiya;
    @Bind(R.id.left_line)
    View leftLine;
    @Bind(R.id.rl_yidiya)
    RelativeLayout rlYidiya;
    @Bind(R.id.tv_evaluate_recode)
    TextView tvEvaluateRecode;
    @Bind(R.id.right_line)
    View rightLine;
    @Bind(R.id.rl_evaluate_recode)
    RelativeLayout rlEvaluateRecode;
    @Bind(R.id.tv_select_house_desc)
    TextView tvSelectHouseDesc;
    @Bind(R.id.look_more)
    TextView lookMore;
    @Bind(R.id.id_recyclerview_house)
    RecyclerView idRecyclerviewHouse;
    @Bind(R.id.time_viewpager)
    ViewPager timeViewpager;
    @Bind(R.id.rl_time_container)
    RelativeLayout rlTimeContainer;
    @Bind(R.id.et_loan_limit)
    EditText etLoanLimit;
    @Bind(R.id.tv_month_rate)
    TextView tvMonthRate;
    @Bind(R.id.tv_month_interest)
    TextView tvMonthInterest;
    @Bind(R.id.tv_beyond)
    TextView tvByond;
    @Bind(R.id.tv_no_date)
    TextView tvNoDate;
    @Bind(R.id.btn_loan_submit)
    Button btnLoanSubmit;
    @Bind(R.id.rl_comment_title)
    RelativeLayout rlCommentTitle;
    @Bind(R.id.sv_container)
    ScrollView svContainer;
    private boolean mHidden;
    private boolean startForResult = false;//增加一个字段控制网络请求，在调用onActivityResult是，不调用DoNetWork
    private BaseDialog loginDialog;
    private BaseDialog authDialog;
    private BaseDialog unBindBankCardDialog;
    private BaseDialog noApplyDialog;
    private boolean showBackIcon = false;

    private String[] month;
    private HouseGalleryAdapter mAdapter;
    private double monthRate;
    private LoanApplyRequest request;
    private double percentage;
    private List<HouseOrRecordBean> dateList = new ArrayList<>();
    private List<HouseOrRecordBean> recordList = new ArrayList<>();
    private List<HouseOrRecordBean> houseList = new ArrayList<>();
    private String[] monthDate;
    private int selectView = R.id.rl_yidiya;
    private float maxLimitAmount; //最大可贷额度
    private HouseOrRecordBean selectedLoanItem;
    private int defalutMonth = 1;
    private boolean isAuto = false; //是否实名认证

    @Override
    public int getLayoutResouceId() {
        return R.layout.fragment_loan_apply_2v;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
//        ImmersionBar.with(this).
//                //单独指定软键盘模式
//                        keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
//                .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
//                    @Override
//                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                        Logger.e(isPopup + "");  //isPopup为true，软键盘弹出，为false，软键盘关闭
//                    }
//                }).statusBarDarkFont(true,0.2f).init();
        initInnerView();
        return rootView;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.rl_back, R.id.rl_yidiya, R.id.rl_evaluate_recode, R.id.btn_loan_submit, R.id.look_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                getActivity().finish();
                break;
            case R.id.rl_yidiya: //已抵押

                tvSelectHouseDesc.setText("选择抵押房产");
                selectView = R.id.rl_yidiya;
                dateList.clear();
                dateList.addAll(houseList);

                clearDateAndSetTextView();

                if (dateList.size() < 5) {
                    lookMore.setVisibility(View.GONE);
                } else if (dateList.size() >= 5) {
                    lookMore.setVisibility(View.VISIBLE);
                }

                tvEvaluateRecode.setTextColor(getContext().getResources().getColor(R.color.gray));
                rightLine.setBackgroundColor(getContext().getResources().getColor(R.color.white));
                tvYidiya.setTextColor(getContext().getResources().getColor(R.color.orange));
                leftLine.setBackgroundColor(getContext().getResources().getColor(R.color.orange));
                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                break;
            case R.id.rl_evaluate_recode:  //评估记录
                tvSelectHouseDesc.setText("选择评估记录");

                selectView = R.id.rl_evaluate_recode;
                dateList.clear();
                dateList.addAll(recordList);

                clearDateAndSetTextView();

                if (dateList.size() < 5) {
                    lookMore.setVisibility(View.GONE);
                } else if (dateList.size() >= 5) {
                    lookMore.setVisibility(View.VISIBLE);
                }

                tvEvaluateRecode.setTextColor(getContext().getResources().getColor(R.color.orange));
                rightLine.setBackgroundColor(getContext().getResources().getColor(R.color.orange));
                tvYidiya.setTextColor(getContext().getResources().getColor(R.color.gray));
                leftLine.setBackgroundColor(getContext().getResources().getColor(R.color.white));

                if (mAdapter != null)
                    mAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_loan_submit:

                if (isAuto) {

                    if (!SpConfig.getInstance().getBool(Constants.BANKSTATE_BOOLEAN)) {
                        showBindBankCardDialog();
                        return;
                    }

                    loanApply();
                } else {
                    showAutoDialog();
                }
                break;
            case R.id.look_more:

                startForResult = true;
                if (selectView == R.id.rl_yidiya) {
//                    openActivity(HouseListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isFromLoanFragment", true);
                    Intent intent = new Intent(mActivity, HouseListActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 10086);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isFromLoanFragment", true);
                    Intent intent = new Intent(mActivity, EvaluateRecordActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 10086);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == EvaluateRecordActivity.RECORD_RESULT_CORD) {
            EvaluateRecordBean recordBean = data.getExtras().getParcelable("recordInfo");
            HouseOrRecordBean houseOrRecordBean = new HouseOrRecordBean();
            houseOrRecordBean.setHouseNo(recordBean.getId());
            houseOrRecordBean.setHouseAddress(recordBean.getResidentialArea());
            houseOrRecordBean.setFainalAssAmount(recordBean.getTotalAmount());
            houseOrRecordBean.setRate(recordBean.getRate());
            houseOrRecordBean.setPercentage(recordBean.getPercentage());
            houseOrRecordBean.setSelected(true);

            for (HouseOrRecordBean bean : recordList) {
                bean.setSelected(false);
            }

            recordList.add(0, houseOrRecordBean);
            dateList.clear();
            dateList.addAll(recordList);
            mAdapter.notifyDataSetChanged();
            clearDateAndSetTextView();
        }

        if (resultCode == HouseListActivity.HOUSE_RESULT_CORD) {
            HouseListRespond.DataBean.HouseLoansBean houseInfo = data.getExtras().getParcelable("houseInfo");

            HouseOrRecordBean houseOrRecordBean = new HouseOrRecordBean();
            houseOrRecordBean.setHouseNo(houseInfo.getId());
            houseOrRecordBean.setHouseAddress(houseInfo.getResidentialArea());
            houseOrRecordBean.setFainalAssAmount(houseInfo.getFainalAssAmount());
            houseOrRecordBean.setRate(houseInfo.getRate());
            houseOrRecordBean.setPercentage(houseInfo.getPercentage());
            houseOrRecordBean.setSelected(true);

            for (HouseOrRecordBean bean : houseList) {
                bean.setSelected(false);
            }

            houseList.add(0, houseOrRecordBean);
            dateList.clear();
            dateList.addAll(houseList);
            mAdapter.notifyDataSetChanged();
            clearDateAndSetTextView();
        }

//        startForResult = false;

        BaseApplicationLike.getMainThreadHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startForResult = false;
            }
        }, 1000);
    }

    private void clearDateAndSetTextView() {
        if (dateList.size() > 0) {

            if (dateList.size() < 5) {
                lookMore.setVisibility(View.GONE);
            } else if (dateList.size() >= 5) {
                lookMore.setVisibility(View.VISIBLE);
            }

            for (HouseOrRecordBean bean :
                    dateList) {
                bean.setSelected(false);
            }
            dateList.get(0).setSelected(true);

            refreshHintView(dateList.get(0));

            tvNoDate.setVisibility(View.GONE);
        } else {
            lookMore.setVisibility(View.GONE);
            tvNoDate.setVisibility(View.VISIBLE);
            if (selectView == R.id.rl_yidiya) {
                tvNoDate.setText("暂无抵押房产");
            } else {
                tvNoDate.setText("暂无评估记录");
            }
            tvMonthRate.setText("月利率：--%");
            tvMonthInterest.setText("月利息：---");
            setSpecialHint("预计可贷额度0元");
        }
    }


    protected void initInnerView() {
        tvTitle.setText("申请贷款");
        setSpecialHint("预计可贷额度0元");

        etLoanLimit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && s.length() > 0 && selectedLoanItem != null) {

                    String rate = selectedLoanItem.getRate();
                    float parseFloat = Float.parseFloat(rate);
                    float loanAmount = Float.parseFloat(s.toString()) * 10000;
                    tvMonthInterest.setText("月利息：" + (int) (loanAmount * parseFloat / 100) + "元");

                } else {
                    tvMonthInterest.setText("月利息：---");
//                    tvByond.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        if (showBackIcon) {
            rlBack.setVisibility(View.VISIBLE);
        } else {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rlCommentTitle.getLayoutParams();
            params.topMargin = DensityUtil.getTitleBarHeight(mActivity);//获取状态蓝高度
            rlCommentTitle.setLayoutParams(params);
            rlBack.setVisibility(View.GONE);
        }

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        idRecyclerviewHouse.setLayoutManager(linearLayoutManager);


        request = new LoanApplyRequest();
    }

    private void setSpecialHint(String hint) {
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hint);

// 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(12, true);

// 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// 设置hint
        etLoanLimit.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
    }


    @Override
    protected void onLazyLoad() {
        super.onLazyLoad();
        Logger.d("onLazyLoad");
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mHidden)
            return;

        if (startForResult)
            return;
        //只会执行一次？？？

        Logger.d("onResume");
        doNetWork();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mHidden = hidden;
        if (!hidden) {

            Logger.d("onHidden");
            doNetWork();
        }
    }

    public void doNetWork() {

        if (svContainer != null)
            svContainer.scrollTo(0, 0);

        //没有登录
        if (TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.SESSIONID_STRING))) {
            houseList.clear();
            recordList.clear();
            dateList.clear();

            if (mAdapter != null)
                mAdapter.notifyDataSetChanged();

            tvMonthRate.setText("月利率：--%");
            tvMonthInterest.setText("月利息：---");
            setSpecialHint("预计可贷额度0元");
            tvNoDate.setVisibility(View.VISIBLE);
            showLoginDialog();
            return;
        }

        toLoanApply();
    }

    /**
     * 登录窗口
     */
    private void showLoginDialog() {
        if (loginDialog == null) {

            loginDialog = new BaseDialog.Builder()
                    .layResuorce(R.layout.dialog_to_login)
                    .animResource(R.style.dialog_animation_fade)
                    .okViewClickEvent(R.id.tv_gologin)
                    .outSideCancel(true)
                    .gravityStyle(Gravity.CENTER)
                    .build();

            loginDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    openActivity(LoginActivity.class);
                    loginDialog.dismiss();
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        loginDialog.show(getFragmentManager(), TAG);
    }

    /**
     * 实名认证窗口
     */
    private void showAutoDialog() {

        if (authDialog == null) {

            authDialog = new BaseDialog.Builder()
                    .layResuorce(R.layout.dialog_to_auto)
                    .animResource(R.style.dialog_animation_fade)
                    .okViewClickEvent(R.id.tv_goauth)
                    .outSideCancel(true)
                    .gravityStyle(Gravity.CENTER)
                    .build();

            authDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    openActivity(RealNameActivity.class);
                    authDialog.dismiss();
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        authDialog.show(getFragmentManager(), TAG);
    }

    /**
     * 弹出银行卡没有绑定窗口
     */
    private void showBindBankCardDialog() {
        if (unBindBankCardDialog == null) {

            unBindBankCardDialog = new BaseDialog.Builder()
                    .layResuorce(R.layout.dialog_to_bind_bankcard)
                    .animResource(R.style.dialog_animation_fade)
                    .okViewClickEvent(R.id.go_binding)
                    .outSideCancel(true)
                    .gravityStyle(Gravity.CENTER)
                    .build();

            unBindBankCardDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    openActivity(AddBankCardActivity.class);
                    unBindBankCardDialog.dismiss();
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        unBindBankCardDialog.show(getFragmentManager(), TAG);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 没有房产窗口
     */
    private void showNoApplyDialog() {
        if (noApplyDialog == null) {

            noApplyDialog = new BaseDialog.Builder()
                    .layResuorce(R.layout.dialog_no_house)
                    .animResource(R.style.dialog_animation_fade)
                    .okViewClickEvent(R.id.btn_submit)
                    .cancelViewClickEvent(R.id.rl_cancel)
                    .gravityStyle(Gravity.CENTER)
                    .outSideCancel(true)
                    .dialogWidth(-2)
                    .build();

            noApplyDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    noApplyDialog.dismiss();
                    openActivity(EvaluateActivity.class);
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        noApplyDialog.show(getFragmentManager(), TAG);
    }

    /**
     * 贷款申请
     */
    public void loanApply() {


        if (dateList.size() < 0) {
            ToastUtil.shortToast(getActivity(), "您还没有房产或评估信息");
            return;
        }

        if (TextUtils.isEmpty(getApplyAmount())) {

            ToastUtil.shortToast(getActivity(), "请填写贷款金额");
            return;
        }

//        if (Float.parseFloat(getApplyAmount()) > maxLimitAmount) {
//            ToastUtil.shortToast(getActivity(), "您输入的金额超过可贷额度，请重新输入");
//            return;
//        }

        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<BaseRespond>() {
            @Override
            public void onNext(BaseRespond subjects) {
                ToastUtil.shortToast(mActivity, subjects.getResDesc());
                openActivity(WaitAuditActivity.class);
            }

            @Override
            public void onError(Throwable e) {
            }
        };

        HashMap<String, Object> fieldsMap = new HashMap<>();

        fieldsMap.put("houseNo", getHouseId());
        fieldsMap.put("applyAmount", getApplyAmount());
        fieldsMap.put("applyDeadline", getTime());
        fieldsMap.put("deadlineType", getUnit());
        request.loanApply(new ProgressSubscriber(onNextListener, mActivity), fieldsMap);
    }


    private String getHouseId() {

        for (HouseOrRecordBean bean : dateList) {
            if (bean.isSelected()) {
                return bean.getHouseNo();
            }
        }
        return null;
    }

    private String getApplyAmount() {
        return Float.parseFloat(etLoanLimit.getText().toString().trim()) * 10000 + "";
    }

    private String getTime() {
        return monthDate[timeViewpager.getCurrentItem()];
    }

    //1表示月份
    private String getUnit() {
        return "1";
    }


    /**
     * 贷款申请
     */
    public void toLoanApply() {
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<ToApplyLoanRespond>() {
            @Override
            public void onNext(ToApplyLoanRespond date) {

                if ("200".equals(date.getResCode()) || "201".equals(date.getResCode())) {

                    isAuto = "201".equals(date.getResCode()) ? false : true;

                    houseList.clear();
                    recordList.clear();
                    dateList.clear();

                    //房产记录
                    List<ToApplyLoanRespond.DataBean.OlAssessmentInfosBean> houseInfoPojos = date.getData().getHouseInfoPojos();

                    if (houseInfoPojos != null && houseInfoPojos.size() > 0) {
                        for (ToApplyLoanRespond.DataBean.OlAssessmentInfosBean bean :
                                houseInfoPojos) {
                            HouseOrRecordBean houseOrRecordBean = new HouseOrRecordBean();
                            houseOrRecordBean.setHouseNo(bean.getHouseNo());
                            houseOrRecordBean.setHouseAddress(bean.getHouseAddress());
                            houseOrRecordBean.setFainalAssAmount(bean.getFainalAssAmount());
                            houseOrRecordBean.setRate(bean.getRate());
                            houseOrRecordBean.setPercentage(bean.getPercentage());
                            houseOrRecordBean.setIsRecord("1");
                            houseOrRecordBean.setSelected(false);
                            houseList.add(houseOrRecordBean);
                        }
                    }

                    //评估记录
                    List<ToApplyLoanRespond.DataBean.OlAssessmentInfosBean> olAssessmentInfos = date.getData().getOlAssessmentInfos();
                    if (olAssessmentInfos != null && olAssessmentInfos.size() > 0) {
                        for (ToApplyLoanRespond.DataBean.OlAssessmentInfosBean bean :
                                olAssessmentInfos) {
                            HouseOrRecordBean houseOrRecordBean = new HouseOrRecordBean();
                            houseOrRecordBean.setHouseNo(bean.getHouseNo());
                            houseOrRecordBean.setHouseAddress(bean.getHouseAddress());
                            houseOrRecordBean.setFainalAssAmount(bean.getFainalAssAmount());
                            houseOrRecordBean.setRate(bean.getRate());
                            houseOrRecordBean.setPercentage(bean.getPercentage());
                            houseOrRecordBean.setIsRecord("0");
                            houseOrRecordBean.setSelected(false);
                            recordList.add(houseOrRecordBean);
                        }
                    }
                    if (houseList.size() > 0) {
                        dateList.clear();
                        dateList.addAll(houseList);
                        selectView = R.id.rl_yidiya;

                        tvEvaluateRecode.setTextColor(getContext().getResources().getColor(R.color.gray));
                        rightLine.setBackgroundColor(getContext().getResources().getColor(R.color.white));
                        tvYidiya.setTextColor(getContext().getResources().getColor(R.color.orange));
                        leftLine.setBackgroundColor(getContext().getResources().getColor(R.color.orange));
                    }

                    if (recordList.size() > 0) {
                        dateList.clear();
                        dateList.addAll(recordList);
                        selectView = R.id.rl_evaluate_recode;

                        tvEvaluateRecode.setTextColor(getContext().getResources().getColor(R.color.orange));
                        rightLine.setBackgroundColor(getContext().getResources().getColor(R.color.orange));
                        tvYidiya.setTextColor(getContext().getResources().getColor(R.color.gray));
                        leftLine.setBackgroundColor(getContext().getResources().getColor(R.color.white));
                    }

                    clearDateAndSetTextView();

                    selectedLoanItem = dateList.get(0);
                    monthDate = date.getData().getLoanTime().split(",");
                    month = new String[monthDate.length];
                    for (int i = 0; i < monthDate.length; i++) {
                        month[i] = monthDate[i] + "个月";
                        if ("3".equals(monthDate[i])) { //默认选中3个月
                            defalutMonth = i;
                        }
                    }

                    timeViewpager.setOffscreenPageLimit(3);
                    timeViewpager.setAdapter(new MonthSelectAdapter());
                    timeViewpager.setPageTransformer(true, new ScaleInTransformer());

                    rlTimeContainer.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            return timeViewpager.dispatchTouchEvent(event);
                        }
                    });

                    timeViewpager.setCurrentItem(defalutMonth);
                    setOrRefreshAdapter();
//
//                } else if ("201".equals(date.getResCode())) {
//
//                    houseList.clear();
//                    recordList.clear();
//                    dateList.clear();
//
//                    if (mAdapter != null)
//                        mAdapter.notifyDataSetChanged();
//
//                    showAutoDialog();
                } else {
                    houseList.clear();
                    recordList.clear();
                    dateList.clear();

                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();

                    showNoApplyDialog();
                }
            }

            @Override
            public void onError(Throwable e) {

            }
        };

        HashMap<String, Object> fieldsMap = new HashMap<>();
        fieldsMap.put("oPageNum", "1");
        fieldsMap.put("oPageSize", "5");
        fieldsMap.put("hPageNum", "1");
        fieldsMap.put("hPageSize", "5");
        request.toLoanApply(new ProgressSubscriber(onNextListener, mActivity), fieldsMap);
    }

    private void setOrRefreshAdapter() {

        if (mAdapter == null) {
            mAdapter = new HouseGalleryAdapter(mActivity, dateList);
            idRecyclerviewHouse.setAdapter(mAdapter);
            mAdapter.setOnItemClick(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    for (int i = 0; i < dateList.size(); i++) {
                        if (i == position) {
                            dateList.get(i).setSelected(true);
                            selectedLoanItem = dateList.get(i);
                            idRecyclerviewHouse.smoothScrollToPosition(position);

                            refreshHintView(dateList.get(i));

                        } else {
                            dateList.get(i).setSelected(false);
                        }
                    }
                    mAdapter.notifyDataSetChanged();

                }

            });
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 刷新提示相关的View
     *
     * @param bean
     */
    private void refreshHintView(HouseOrRecordBean bean) {
        float amount = Float.parseFloat(bean.getFainalAssAmount());
        String percentage = bean.getPercentage();
        float percentageFloat = Float.parseFloat(percentage) / 100;

        String rate = bean.getRate();
        float rateFloat = Float.parseFloat(rate);

        maxLimitAmount = amount = amount * percentageFloat;
        if (amount >= 10000) {
            setSpecialHint("预计可贷额度" + NumUilt.formatFloat(amount / 10000) + "万元");
        } else {
            setSpecialHint("预计可贷额度" + NumUilt.formatFloat(amount) + "元");
        }
        tvMonthRate.setText("月利率：" + rate + "%");
//        tvMonthInterest.setText("月利息：" + (int) (amount * rateFloat / 100) + "元");
        etLoanLimit.setText("");
    }

    /**
     * 显示回退按钮
     *
     * @param showBack
     */
    public void showBackIcon(boolean showBack) {
        this.showBackIcon = showBack;
    }

    public class MonthSelectAdapter extends PagerAdapter {

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final TextView view = new TextView(getContext());
            view.setTextSize(DensityUtil.dip2px(getContext(), 12));

            view.setText(month[position]);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(lp);
            view.setGravity(Gravity.CENTER);

            container.addView(view);

//            view.setOnTouchListener(new View.OnTouchListener() {
//
//                private float startY;
//                private float startX;
//
//                @Override
//                public boolean onTouch(View v, MotionEvent event) {
//                    switch (event.getAction()){
//                        case MotionEvent.ACTION_DOWN:
//                            startX = event.getRawX();
//                            startY = event.getRawY();
//                            break;
//
//                        case MotionEvent.ACTION_UP:
//                        case MotionEvent.ACTION_CANCEL:
//                            //出发点击事件
//                            if(event.getRawX() == startX && event.getRawY() == startY){
//                                if(startX <= DensityUtil.getScreenWidth(mActivity)/3){//点击左边
//                                    timeViewpager.setCurrentItem(timeViewpager.getCurrentItem() - 1);
//                                }else if(startX >= DensityUtil.getScreenWidth(mActivity)*2/3){//点击右边
//                                    timeViewpager.setCurrentItem(timeViewpager.getCurrentItem() + 1);
//                                }
//                            }
//                            startX = 0;
//                            startY = 0;
//                            break;
//                    }
//                    return true;
//                }
//            });
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return month.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }
    }

}
